﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Siser.Web.Security
{
    public static class Encryption
    {
        /// <summary>
        /// Encripta con Sha1 un valor string
        /// </summary>
        /// <param name="value">Valor que se va a encriptar</param>
        /// <returns><c>value</c> encriptado con Sha1</returns>
        public static string encryptSha1(string value)
        {
            Byte[] bytes = System.Text.Encoding.Unicode.GetBytes(value);
            System.Security.Cryptography.SHA1CryptoServiceProvider sha1 = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            Byte[] hash = sha1.ComputeHash(bytes);

            return System.Convert.ToBase64String(hash);
        }
    
        /// <summary>
        /// Encripta con AES un valor string
        /// </summary>
        /// <param name="value">Valor que se va a encriptar</param>
        /// <param name="key">Llave privada para encriptar</param>
        /// <returns><c>value</c> encriptado con AES</returns>
        public static string encryptAES(string value, string key) 
        {
            System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();
            Byte[] _value = null;
            string result;

            _value = System.Text.Encoding.UTF8.GetBytes(value);

            key = Encryption.encryptSha1(key).PadRight(32, '=');
            AES.Key = System.Text.Encoding.ASCII.GetBytes(key);
            AES.IV = System.Text.Encoding.ASCII.GetBytes(key.Substring(12, 16));

            result = System.Convert.ToBase64String(AES.CreateEncryptor().TransformFinalBlock(_value, 0, _value.Length));
            AES.Clear();
            return result;
        }

        /// <summary>
        /// Desencripta con AES un valor string
        /// </summary>
        /// <param name="value">Valor encriptado que se va a desencriptar</param>
        /// <param name="key">Llave privada para desencriptar</param>
        /// <returns><c>value</c> desencriptado con AES</returns>
        public static string decryptAES(string value, string key)
        {
            System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();
            Byte[] _value = null;
            string result;
        
            _value = System.Convert.FromBase64String(value);

            key = Encryption.encryptSha1(key).PadRight(32, '=');
            AES.Key = System.Text.Encoding.ASCII.GetBytes(key);
            AES.IV = System.Text.Encoding.ASCII.GetBytes(key.Substring(12, 16));

            result = System.Text.Encoding.UTF8.GetString(AES.CreateDecryptor().TransformFinalBlock(_value, 0, _value.Length));
            AES.Clear();
            return result;
        }
    }
}